<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.7
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############






JFX::checkAdminPermsRedirect('core', 'perm_grant_permissions');

$THEME->addBreadcrumb($this->adminUrl.'/perms/', $this->lang('ap_title_perms'));

$userid = (int) get('user');
$workspaceid = (int) get('workspace');

if($DB->countRows($CONFIG->dbprefix.'admin_users', "id = '{$userid}'")==0){
    $userid = 0;
}

if($DB->countRows($CONFIG->dbprefix.'workspaces', "id = '{$workspaceid}'")==0){
    $workspaceid = 0;
}



if($userid != 0 && $workspaceid != 0 && count($_POST)>0){
    // form submitted
    $perms = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}admin_users_to_permissions WHERE workspace_id = '{$workspaceid}' AND user_id = '{$userid}'");
    $origPerms = array();
    foreach($perms as $k=>$v){
        $origPerms[$v['module_key'].':|:'.$v['permission_key']] = '';
    }
    foreach($_POST as $k=>$v){
        if($k=='pageperms'){
            foreach($v as $key=>$value){
                // lets process the page permissions
                $pageid = (int) $value;
                if(array_key_exists('core:perm_page_'.$workspaceid.'_'.$pageid, $origPerms)){
                    unset($origPerms['core:perm_page_'.$workspaceid.'_'.$pageid]);
                }
                $dbParams = array(
                    'user_id' => $userid,
                    'workspace_id' => $workspaceid,
                    'module_key' => 'core',
                    'permission_key' => 'perm_page_'.$workspaceid.'_'.$pageid
                );
                if($DB->countRows($CONFIG->dbprefix.'admin_users_to_permissions', "user_id = '{$userid}' AND workspace_id = '{$workspaceid}' AND module_key = 'core' AND permission_key = 'perm_page_{$workspaceid}_{$pageid}'")==0){
                    $DB->insert($CONFIG->dbprefix.'admin_users_to_permissions', $dbParams);
                }
                unset($origPerms['core:|:perm_page_'.$workspaceid.'_'.$pageid]);
                continue;
            }
        }

        $k = explode(':|:', $k);
        $moduleKey = $k[0];
        $label = $k[1];
        if($v == 1){
            // grant permission
            if($DB->countRows($CONFIG->dbprefix.'admin_users_to_permissions', "user_id = '{$userid}' AND workspace_id = '{$workspaceid}' AND module_key = '{$moduleKey}' AND permission_key = '{$label}'")==0){
                // lets insert
                $dbParams = array(
                    'user_id' => $userid,
                    'workspace_id' => $workspaceid,
                    'module_key' => $moduleKey,
                    'permission_key' => $label
                );
                $DB->insert($CONFIG->dbprefix.'admin_users_to_permissions', $dbParams);
            }
            unset($origPerms[$moduleKey.':|:'.$label]);
        }
    }
    // get rid of leftover permissions
    foreach($origPerms as $k=>$v){
        $k = explode(':|:', $k);
        $moduleKey = $k[0];
        $label = $k[1];
        $DB->delete($CONFIG->dbprefix.'admin_users_to_permissions', "user_id = '{$userid}' AND workspace_id = '{$workspaceid}' AND module_key = '{$moduleKey}' AND permission_key = '{$label}'");
    }
    JFX::addSuccess('Permissions updated!');
    JFX::redirect(THIS_PAGE_URL);
}

$users = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}admin_users ORDER BY username ASC");
$userOpts = array('0'=>'Select a User');
foreach($users as $k=>$v){
    $userOpts[$v['id']] = $v['username'];
};

$userSelect = '<select id="jfx-user-perms-select">';
foreach($userOpts as $k=>$v){
    if($k==$userid) $selected = 'selected="selected"';
    else $selected = '';
    $userSelect .= '<option value="'.$k.'" '.$selected.'>'.$v.'</option>';
}
$userSelect .= '</select>';

$workspaces = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}workspaces ORDER BY title ASC");
$wsOpts = array('0' => 'Select a Workspace');
foreach($workspaces as $k=>$v){
    $wsOpts[$v['id']] = $v['title'];
};

$wsSelect = '<select id="jfx-workspace-perms-select">';
$wsOptString = '';
foreach($wsOpts as $k=>$v){
    if($k==$workspaceid) $selected = 'selected="selected"';
    else $selected = '';
    $wsSelect .= '<option value="'.$k.'" '.$selected.'>'.$v.'</option>';
}
$wsSelect .= '</select>';


$VIEW->addJs('
$(document).ready(function(){
    $("#jfx-user-perms-select").change(function(){
        window.location = "'.$CONFIG->adminUrl.'/perms?user='.'"+this.options[this.selectedIndex].value+"&workspace='.$workspaceid.'";
    });
    $("#jfx-workspace-perms-select").change(function(){
        window.location = "'.$CONFIG->adminUrl.'/perms?user='.$userid.'&workspace="+this.options[this.selectedIndex].value;
    });
    $("#jfx-admin-perms-tree input[type=checkbox]").change(function(){
        if(this.checked){
            $("table input[type=checkbox]", this.parentNode).each(function(){
                $(this).attr("checked", true);

            });
        }else{
            $("table input[type=checkbox]", this.parentNode).each(function(){
                $(this).attr("checked", false);
            });
        }
    });
});
');


echo $userSelect;
echo $wsSelect;
echo '<ul><li>User: '.$DB->oneValue($CONFIG->dbprefix.'admin_users', 'username', "id = '{$userid}'").'</li>
        <li>Workspace: '.$DB->oneValue($CONFIG->dbprefix.'workspaces', 'title', "id = '{$workspaceid}'").'</li></ul>';


if(get('user')==0 || get('workspace')==0){
    // show the menu only

}else{
    // show the permissions arrays

    $userid = (int) get('user');
    $workspaceid = (int) get('workspace');

    if($DB->countRows($CONFIG->dbprefix.'admin_users', "id = '{$userid}'")==0){
        JFX::redirect($CONFIG->adminUrl.'/perms?workspace='.$workspaceid);
    }
    if($DB->countRows($CONFIG->dbprefix.'workspaces', "id = '{$workspaceid}'")==0){
        JFX::redirect($CONFIG->adminUrl.'/perms?user='.$userid);
    }


    $col1 = array();
    $col2 = array();
    $col3 = array();
    $col4 = array();

    $perms = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}admin_permissions ORDER BY module_key ASC, keyname ASC");

    $modulePerms = array();
    $curModule = $perms[0]['module_key'];
    $curModuleCount = 0;
    $modulePerms[$curModuleCount] = array('title' => $curModule, 'perms'=>array());
    foreach($perms as $k=>$v){
        if($curModule !== $v['module_key']){
            $curModule = $v['module_key'];
            $curModuleCount++;
            $modulePerms[$curModuleCount] = array('title' => $v['module_key'], 'perms' => array());
        }
        $count = count($modulePerms[$curModuleCount]['perms']);
        $checked = (bool) $DB->countRows($CONFIG->dbprefix.'admin_users_to_permissions', "user_id = '{$userid}' AND module_key = '{$v['module_key']}' AND permission_key = '{$v['keyname']}' AND workspace_id = '{$workspaceid}'");
        $modulePerms[$curModuleCount]['perms'][$count] = $v;
        $modulePerms[$curModuleCount]['perms'][$count]['checked'] = $checked;
        $modulePerms[$curModuleCount]['perms'][$count]['title'] = $LANG->get($v['module_key'], $v['keyname']);
    }

    $SMARTY->assign('perms', $modulePerms);
    $SMARTY->assign('permFormAction', $CONFIG->adminUrl.'/perms?user='.$userid.'&amp;workspace='.$workspaceid);

$pages = JFX::getPageTree(0, $workspaceid);


$tableRows = JFX_AdminPermsMakePageCheckboxes($pages, $workspaceid, $userid);

$SMARTY->assign('tableRows', $tableRows);


    echo $SMARTY->fetch('admin/perms.tpl');




}




?>
<div class="jfx-clear"></div>


















<?php

function JFX_AdminPermsMakePageCheckboxes($pages, $workspaceid, $userid, $depth=0){
    $LANG = JFX::registry('lang');
    $DB = JFX::registry('db');
    $CONFIG = JFX::registry('config');
    $USER = JFX::registry('JFX_User');
    $retval = '';
    foreach($pages as $k=>$v){
        $checked = ($DB->countRows($CONFIG->dbprefix.'admin_users_to_permissions', "user_id = '{$userid}' AND workspace_id = '{$workspaceid}'
            AND module_key = 'core' AND permission_key = 'perm_page_{$workspaceid}_{$v['id']}'")>0) ? 'checked="checked"' : '';
        $retval .= '<tr><td>'.str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', $depth).'
            <input type="checkbox" name="pageperms[]" value="'.$v['id'].'" '.$checked.' />';
        $retval .= $LANG->getContent('core', 'page_title', $v['id'], '', $workspaceid);
        if(count($v['subpages'])>0){
            $retval .= '<table><tbody>';
            $retval .= JFX_AdminPermsMakePageCheckboxes($v['subpages'], $workspaceid, $userid, $depth+1);
            $retval .= '</tbody></table>';
        }
        $retval .= '</td></tr>';
    }
    return $retval;
}




